package com.h2cloud.JUCTest.Semaphore;

/**
 * @Package: com.h2cloud.JUCTest.Semaphore
 * @ClassName: SemaphoreDemo
 * @Author: h2cloud
 * @CreateTime: 2022/9/25 11:00 上午
 * @Description:
 */
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.Semaphore;

@Slf4j
class MyThread extends Thread {
	private Semaphore semaphore;

	public MyThread(String name, Semaphore semaphore) {
		super(name);
		this.semaphore = semaphore;
	}

	@Override
	public void run() {
		int count = 3;
		log.info(Thread.currentThread().getName() + " trying to acquire");
		try {
			semaphore.acquire(count);
			log.info(Thread.currentThread().getName() + " acquire successfully");
			Thread.sleep(1000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		} finally {
			semaphore.release(count);
			log.info(Thread.currentThread().getName() + " release successfully");
		}
	}
}

@Slf4j
public class SemaphoreDemo {
	public final static int SEM_SIZE = 10;

	public static void main(String[] args) {
		Semaphore semaphore = new Semaphore(SEM_SIZE);
		MyThread t1 = new MyThread("t1", semaphore);
		MyThread t2 = new MyThread("t2", semaphore);
		t1.start();
		t2.start();
		int permits = 5;
		log.info(Thread.currentThread().getName() + " trying to acquire");
		try {
			semaphore.acquire(permits);
			log.info(Thread.currentThread().getName() + " acquire successfully");
			Thread.sleep(1000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		} finally {
			semaphore.release();
			log.info(Thread.currentThread().getName() + " release successfully");
		}
	}
}

